package com.gaohe.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.gaohe.common.R;
import com.gaohe.pojo.ShoppingCart;
import com.gaohe.pojo.User;
import com.gaohe.service.ShoppingCartService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.List;

@RestController
@Slf4j
@RequestMapping("/shoppingCart")
public class ShoppingController {
    @Autowired
    private ShoppingCartService shoppingCartService;

    //购物车展示
    @GetMapping("/list")
    public R<List<ShoppingCart>> shoppingCart(HttpServletRequest request) {
        //根据userId来查询个人的购物车
        User user = (User) request.getSession().getAttribute("user");
        LambdaQueryWrapper<ShoppingCart> lqw = new LambdaQueryWrapper();
        lqw.eq(ShoppingCart::getUserId, user.getId());
        List<ShoppingCart> shoppingCarts = shoppingCartService.list(lqw);
        return R.success(shoppingCarts);
    }

    //添加购物车
    @PostMapping("/add")
    public R<String> addShopping(@RequestBody ShoppingCart shoppingCart, HttpServletRequest request) {
        shoppingCartService.addShoppingCarts(shoppingCart, request);
        return R.success("购物车添加成功");
    }

    //减少购物车餐品数量
    @PostMapping("sub")
    public R<String> subShopping(@RequestBody ShoppingCart shoppingCart, HttpServletRequest request) {
        shoppingCartService.subShoppingCarts(shoppingCart, request);
        return R.success("减少成功");
    }

    //清空操作
    @DeleteMapping("clean")
    public R<String> deleteAll(HttpServletRequest request) {
        User user = (User) request.getSession().getAttribute("user");
        LambdaQueryWrapper<ShoppingCart> lqw = new LambdaQueryWrapper<>();
        lqw.eq(ShoppingCart::getUserId, user.getId());
        shoppingCartService.remove(lqw);
        return R.success("清空成功");
    }
}
